/**
 * @ author: 汪孟苹
 */
define(['jquery','bbcare',"oms_config/root","fu/app/comm/comm"],function($,$bb,$root,$comm){
	var servers = {};
	var URL = $bb.baseUrl("followup");

	/**
	 * 请求专科袋患者列表
	 */
	servers.ajaxPatients = function(keyword,callback){
		$bb.ajax({
			url: URL + "followup/service/patient/patientQueueListQuery",
			data:JSON.stringify({
				data : {
					"page":1,
					"rows":20,
					"flag":"2",
					"patientName":keyword
				}
			}),
			success: function(data){
				if(data.success){
					callback(data.data.rows);	
				}else{
					$bb.toastShow("请求专科袋患者列表出错！");
				}
			}
		});
	}

	/**
	 * 请求患者的categoryList
	 */
	servers.ajaxCategoryList = function(params,callback){
		$bb.ajax({
			url: URL + "followup/service/patient/patientContentCategoryListQuery",
			data:JSON.stringify({
				data : {
					"patientSchemeId":params.patientSchemeId
				}
			}),
			success: function(data){
				if(data.success){
					callback(params,data.data.rows);	
				}else{
					$bb.toastShow("请求专科袋患者categoryList出错！");
				}
			}
		});
	}

	/**
	 * 请求患者某个category的数据
	 */
	servers.ajaxCategoryDetail = function(params,callback){
		if(params.questionnaireId){
			$(".followUp-subtit, .followUp-Content").show();
			$bb.ajax({
				url: URL + "followup/service/patient/patientContentDetailQuery",
				data:JSON.stringify({
					data : params
				}),
				success: function(data){
					if(data.success){
						callback(data.data);
					}else{
						$bb.toastShow("请求专科袋患者category详情出错！");
					}
				}
			});
		}else{
			$(".followUp-subtit, .followUp-Content").hide();
		}
	}

	/**
	 * 处理专科袋患者基本信息
	 */
	servers.basicInfoData = function(obj){
		var config = $root.init();
		obj.genderPic = (obj.gender == "N"? "boy":"girl");
		obj.genderShow = (obj.gender == "N"? "男":"女");
		obj.width = 100 / obj.totalNum + '%';
		if(obj.taskStatusArr && typeof obj.taskStatusArr == "string"){	// 由于taskStatusArr字段是后加的，导致之前的数据会出错，所以在这里判断一下
			obj.taskStatusArr = JSON.parse(obj.taskStatusArr);
			for (var i = 0; i < obj.taskStatusArr.length; i++) {
				if(obj.taskStatusArr[i] == '0'){
					obj.taskStatusArr[i] = "progress-notstart";
				}else if(obj.taskStatusArr[i] == '1'){
					obj.taskStatusArr[i] = "progress-finish";
				}else if(obj.taskStatusArr[i] == '2'){
					obj.taskStatusArr[i] = "progress-overdue";
				}
			}
		}
		obj.gestationShow = config.dom.specialtyBagGestation;	//孕周是否显示
		return obj;
	}

	/**
	 * 处理专科袋患者categoryList列表信息
	 */
	servers.categoryListData = function(list){
		var config = $root.init();
		var data = {
			rows: list,
			flag: config.dom.specialtyBagCollect
		}
		return data;
	}
	
	/**
     * question_growthComplex题型 数据处理
     */
    var growthComplexData = function(params){
        var arr = [];
        var children_default = {
            "subType": ["question_calc","question_text","question_text"],
        };
        params = $.extend(children_default,params);
        var length = parseInt(params.length / params.id.length);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.length = length;
            obj.labelLength = params.labelLength;
            obj.label = params.label[i];
            obj.type = params.subType[i];
            arr.push(obj);
        }
        arr[0].calcType = params.calcType;
        arr[0].unit = params.unit;
        return arr;
    }

    /**
     * question_radioInput题型 数据处理
     */
    var radioInputData = function(params){
    	var arr = [];
        var children_default = {
            "subType": ["question_radio","question_text"],
        };
        params = $.extend(children_default,params);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.label = params.label[i];
            obj.length = params.length[i];
            obj.labelLength = params.labelLength;
            obj.type = params.subType[i];
            arr.push(obj);
        }
        arr[0].list = params.list;
        arr[0].val = params.val;
        arr[0].relevantText = params.relevantText;
        arr[1].placeHolder = params.placeHolder;
        return arr;
    }

    /**
     * question_checkboxInput题型 数据处理
     */
    var checkboxInputData = function(params){
    	var arr = [];
        var children_default = {
            "subType": ["question_checkbox","question_text"],
        };
        params = $.extend(children_default,params);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.label = params.label[i];
            obj.length = params.length[i];
            obj.labelLength = params.labelLength;
            obj.type = params.subType[i];
            arr.push(obj);
        }
        arr[0].list = params.list;
        arr[0].val = params.val;
        arr[0].relevantText = params.relevantText;
        arr[1].placeHolder = params.placeHolder;
        return arr;
    }

    /**
	 * 处理表格tbody数据
	 */
	var handleTbodyData = function(list,values,status){
		var arr = [];
		for(var i=0; i<list.length;i++){
			arr[i] = list[i];
			if (arr[i].id && arr[i].id instanceof Array) {
                if(arr[i].type == "question_growthComplex" || arr[i].type == "question_growthSimple"){    // growthComplex、growthSimple 题型
                    arr[i].children = growthComplexData(arr[i]);
                }else if(arr[i].type == "question_radioInput"){
                	arr[i].children = radioInputData(arr[i]);
                }else if(arr[i].type == "question_checkboxInput"){
                	arr[i].children = checkboxInputData(arr[i]);
                }
            }
			if(!arr[i].status){
				arr[i].status = status;
			}
			arr[i].name = arr[i].id;
			if(list[i].children){
				arr[i].children = handleTbodyData(list[i].children,values,arr[i].status);
			}else{
				var arrValue = [];
				for(var p=0; p<values.length; p++){
					if(arr[i].calcType && arr[i].calcType == "00001"){  // 体重因为单位不统一，需要处理
                        if(arr[i].unit && arr[i].unit == "g"){
                        	if(values[p].values[arr[i].id] != undefined && values[p].values[arr[i].id] != "" && values[p].values[arr[i].id] != null){
                        		var n = $comm.getDecimalPlaces(values[p].values[arr[i].id])-3;
                        		if(n < 0) n = 0;
                            	values[p].values[arr[i].id] = (values[p].values[arr[i].id]*1000).toFixed(n);
                        	}
                        }
                    }
                    if(values[p].values[arr[i].id] != undefined && arr[i].type != "question_radio" && arr[i].type != "question_select" && arr[i].type != "question_checkbox"){
                    	values[p].values[arr[i].id] = values[p].values[arr[i].id]; //截取.substring(0,8)
                    }
					arrValue.push(values[p].values[arr[i].id]);
				}
				arr[i].value = arrValue;	
			}
			switch (arr[i].type) {
				case "question_radio":
				case "question_checkbox":
				case "question_radioRelation":
				case "question_checkboxRelation":
				case "question_radioWithInput":
				case "question_checkboxWithInput":
					if( arr[i].list && arr[i].list.length > 0 ){
						arr[i].num = arr[i].list.length;
						for(var j=0;j<arr[i].list.length;j++){
							var str = arr[i].list[j];
								arr[i].list[j] = {};
								arr[i].list[j].text = str;
								arr[i].list[j].status = status;
								arr[i].list[j].index = j;
							var arrValueListRow = [];
							for(var k=0;k<arr[i].value.length;k++){
								arrValueListRow.push(arr[i].value[k]);
							}
							arr[i].list[j].val = arrValueListRow;
							for (var p = 0; p < arr[i].list[j].val.length; p++) {
								if(typeof(arr[i].value[p]) == "string"){
									var subStr = arr[i].list[j].text;
									var str = arr[i].list[j].val[p];
									if(arr[i].type=="question_checkbox" || arr[i].type=="question_checkboxRelation" ){
										if(str.indexOf(subStr)>0){
											arr[i].list[j].val[p] = "true";
										}
									}else if(arr[i].type=="question_radio" || arr[i].type=="question_radioRelation"){
										if(arr[i].list[j].text == str){
											arr[i].list[j].val[p] = "true";
										}
									}else if( arr[i].type=="question_checkboxWithInput" || arr[i].type=="question_radioWithInput" ){
										if( str && str != "" && str != null ){
											var valueArr = JSON.parse(str);
										}
										if(str.indexOf(subStr)>0){
											if( arr[i].relationKey == subStr && valueArr[valueArr.length-1] != "" ){
												arr[i].list[j].val[p] = valueArr[valueArr.length-1];
											}else{
												arr[i].list[j].val[p] = "true";
											}
										}else{
											arr[i].list[j].val[p] = "false";
										}
									}
								}else{
									arr[i].list[j].val[p] = "false";
								}
							}
						}
					}
					break;
				case "question_multiText":
				case "question_multiSelect":
				case "question_address":
				case "question_multiTextSelect":
					for (var j = 0; j < arr[i].value.length; j++) {
						if( arr[i].value[j] && arr[i].value[j] != "" && arr[i].value[j] != null ){
							var valueArr = JSON.parse(arr[i].value[j]);
							var str = "";
							for (var p = 0; p < valueArr.length; p++) {
								if( arr[i].type=="question_multiText" || arr[i].type=="question_multiSelect" ){
									if(valueArr[p]) str += valueArr[p] + arr[i].list[p].subunit;
								}else if( arr[i].type=="question_address" ){
									if(valueArr[p]) str += valueArr[p];
								}else if( arr[i].type=="question_multiTextSelect" ){
									if(valueArr[p]){
										str += valueArr[p];
									}else if( p % 2 == 0 ){
										p++;
									}
								}
							}
							arr[i].value[j] = str;
						}
					}
					break;
				case "question_multiLabelText":
					if( $.isArray(arr[i].label) ) arr[i].label = arr[i].label.join("/");
					for (var j = 0; j < arr[i].value.length; j++) {
						if( arr[i].value[j] && arr[i].value[j] != "" && arr[i].value[j] != null ){
							var valueArr = JSON.parse(arr[i].value[j]);
							arr[i].value[j] = valueArr.join("/");
							if( arr[i].value[j] == "/" ) arr[i].value[j] = "";
						}
					}
					break;
			}
		}
		return arr;
	}
	/**
	 * 整理表格tbody数据
	 */
	servers.tbodyData = function(options){
		var arr = [];
		for(var i=0; i<options.list.length; i++){
			var resultArr = handleTbodyData(options.list[i].children,options.task,options.status)
			arr.push(resultArr);
		}
		var data = {
			children: arr
		}
		return data;
	}

	/**
	 * 安医大新增采集（自定义题型）
	 */
	servers.getSampleData = function(sampleList){
		for (var i = 0; i < sampleList.length; i++) {
			for(var key in sampleList[i]){
				if(key != "sampleType"){
					sampleList[i][key] = sampleList[i][key] == "1" ? "已采集" : "未采集";
				}
			}
		};
		var sampleQuest = [
			{
				children:[
					{id:"ahmuSample0001",label:"尿液",type:"question_text"},
					{id:"ahmuSample0002",label:"血液",type:"question_text"},
					{id:"ahmuSample0003",label:"唾液",type:"question_text"},
					{id:"ahmuSample0004",label:"头发",type:"question_text"}	
				],
				label:"生物样本收集记录",
				type:"qusetion_group"
			}
		];
		var sampleValue = [
			{taskName:"第1次",values:{
				"ahmuSample0001":sampleList[0].sampleValue1,
				"ahmuSample0002":sampleList[1].sampleValue1,
				"ahmuSample0003":sampleList[2].sampleValue1,
				"ahmuSample0004":sampleList[3].sampleValue1
			}},
			{taskName:"第2次",values:{
				"ahmuSample0001":sampleList[0].sampleValue2,
				"ahmuSample0002":sampleList[1].sampleValue2,
				"ahmuSample0003":sampleList[2].sampleValue2,
				"ahmuSample0004":sampleList[3].sampleValue2,
			}},
			{taskName:"第3次",values:{
				"ahmuSample0001":sampleList[0].sampleValue3,
				"ahmuSample0002":sampleList[1].sampleValue3,
				"ahmuSample0003":sampleList[2].sampleValue3,
				"ahmuSample0004":sampleList[3].sampleValue3,
			}}
		];
		return {
			sampleQuest:sampleQuest,
			sampleValue:sampleValue
		}
	}

	return servers;
});
